<template>
  <div id="app" style="display:flex;">
    <div v-if="hasAccount" style="flex:1;display:flex;flex-direction:column;">
      <div style="display:flex;height:200px;">
        <el-card :header="resTitle" style="width:500px;">
          <el-tree :data="resources" @node-click="select"></el-tree>
        </el-card>
        <el-card
          header="分类"
          style="margin-left:5px;flex:1;display: flex;
    flex-direction: column;width:100%;"
          :body-style="{ overflow: 'auto' }"
        >
          <div v-if="categories.length">
            <el-input
              size="small"
              style="width:180px;margin-left:5px;margin-bottom:5px;"
              v-for="item in categories"
              :value="item.name"
              :key="item.name"
              @focus="() => selectCategory(item)"
              readonly
            >
              <el-select
                v-if="item.name != '全部'"
                style="width:100px;"
                v-model="item.status"
                slot="append"
                @change="(val) => createBind(item, val)"
                :placeholder="item.status"
              >
                <el-option
                  v-for="option in options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                ></el-option>
              </el-select>
            </el-input>
          </div>
          <div v-else>
            选择资源库
          </div>
        </el-card>
      </div>
      <el-card
        header="资源管理"
        style="flex:1;margin-top:5px;display:flex;flex-direction:column;"
        :body-style="{ display: 'flex', flex: 1 }"
      >
        <div style="display:flex;flex:1;flex-direction:column">
          <div style="display:flex;height:50px">
            <el-button-group v-if="collecting">
              <el-button
                type="primary"
                :loading="true"
                size="small"
                @click="collect"
              >
                采集中({{ page }}/{{ pageCount }})</el-button
              >
            </el-button-group>
            <el-button-group v-else>
              <el-button type="primary" size="small" @click="collect">
                采集</el-button
              >
              <el-button type="default" size="small" @click="collectToday"
                >采集今日</el-button
              >
              <el-button type="default" size="small" @click="collectRecent"
                >采集最近更新</el-button
              >
            </el-button-group>
          </div>
          <el-table :data="movies" style="flex:1;" height="100%">
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="nickname" label="别名"> </el-table-column>
            <el-table-column prop="company" label="公司"> </el-table-column>
            <el-table-column prop="tv" label="电视台"> </el-table-column>
            <el-table-column prop="category" label="分类"> </el-table-column>
            <el-table-column prop="time" label="时间"> </el-table-column>
            <el-table-column prop="status" label="状态"> </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <div v-else-if="!loading" style="width:500px;height:400px;" class="login">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="后台管理地址" prop="url">
          <el-input v-model="form.url" placeholder="后台管理地址"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            show-password
            v-model="form.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item style="text-align:right">
          <el-button type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else>
      正在加载...
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import qs from "qs";
import { URL } from "url";
import { Console, dir } from "console";
const _ = require("underscore");
const cheerio = require("cheerio");

function Login(account) {
  let data = new FormData();
  data.append("dopost", "login");
  data.append("userid", account.username);
  data.append("pwd", account.password);
  return new Promise((resolver, rejecter) => {
    Vue.http.post(account.url, data).then((response) => {
      if (response.data.includes("成功登录")) {
        resolver(true);
        const fs = require("fs");
        fs.writeFileSync("account.json", JSON.stringify(account));
        return;
      }
      this.$alert("登录失败");
      resolver(false);
    });
  });
}

export default {
  name: "collector",
  data() {
    return {
      hasAccount: false,
      resources: [],
      resTitle: "资源库",
      options: [],
      listUrl: "",
      pageCount: 0,
      page: 1,
      existsTypes: [],
      value: null,
      categories: [],
      bindingCategories: [],
      movies: [],
      collecting: false,
      isRecent: false,
      categoryLoading: false,
      form: {
        url: "",
        username: "",
        password: "",
        host: "",
      },
      loading: true,
      res: null,
      rules: {
        url: [
          { required: true, message: "请输入后台管理地址", trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
        ],
      },
    };
  },
  async created() {
    const fs = require("fs");
    if (!fs.existsSync("account.json")) {
      return;
    }
    const account = fs.readFileSync("account.json", "utf8");
    if (!account) {
      return;
    }
    this.$store.state.account = JSON.parse(account);
    if (!(await Login(this.$store.state.account))) {
      return;
    }
    this.hasAccount = true;
    let apiUrl = this.$store.state.account.host + "/yuet2/api.php";
    let response = await Vue.http.get(apiUrl);
    const cheerio = require("cheerio");
    const $ = cheerio.load(response.data);
    let list = $("#list > tbody > tr > td.bi > a");
    let res = [];
    _.each(list, (r) => {
      let target = $(r)
        .attr("href")
        .split("=");
      res.push({
        label: $(r).text(),
        url: $(r).attr("href"),
        target: target[target.length - 1],
      });
    });
    console.log(res);
    this.resources = res;
  },
  methods: {
    async collect() {
      this.collecting = true;
      await this.checkCollect(false);
      this.collecting = false;
    },
    async collectToday() {
      this.collecting = true;
      await this.checkCollect(true);
      this.collecting = false;
    },
    async collectRecent() {
      this.collecting = true;
      this.isRecent = true;
      await this.checkCollect(true);
      this.collecting = false;
      this.isRecent = false;
    },
    async checkCollect(onlyToday) {
      if (!this.res) {
        return;
      }
      let response = await Vue.http.get(this.res.target);
      const cheerio = require("cheerio");
      let $ = cheerio.load(response.data);
      let types = $("#type a");
      let response1 = await Vue.http.get(
        this.$store.state.account.host + "/yuet2/admin_type.php"
      );
      let exist$ = cheerio.load(response1.data);
      this.existsTypes = [];
      _.each(exist$("td a"), (aEl) => {
        let url = exist$(aEl).attr("href");
        this.existsTypes.push({
          name: exist$(aEl).text(),
          id: url.split("=")[1],
        });
      });
      console.dir(this.existsTypes);
      let newTypes = [];
      _.each(types, (type) => {
        let name = $(type).text();
        if (
          name == "全部" ||
          this.existsTypes.filter((x) => x.name == name).length
        ) {
          return;
        }
        newTypes.push(name);
      });

      if (!newTypes.length) {
        await this.startCollect(onlyToday);
        return;
      }
      this.$alert("以下大分类不存在：" + newTypes.join(","), {
        confirmButtonText: "已添加",
        callback: async (action) => {
          await this.checkCollect(onlyToday);
        },
      });
    },
    async startCollect(onlyToday) {
      let targetHost =
        new URL(this.res.target).protocol +
        "//" +
        new URL(this.res.target).hostname;
      this.movies = [];
      let downloadSourcePage =
        this.$store.state.account.host +
        "/yuet2/admin_playerdown.php?action=boardsource";
      let downloadSource = await Vue.http.get(downloadSourcePage);
      let d$ = cheerio.load(downloadSource.data);
      let rows = d$("#form2 > table > tbody > tr");
      let downloadMap = {};
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        let inputs = d$(row).find("input[type='text']");
        if (!inputs.length) {
          continue;
        }
        console.dir(inputs);
        let name = d$(inputs[0]).val();
        let value = d$(inputs[2]).val();
        if (!name) {
          continue;
        }
        downloadMap[name] = value;
      }
      if (this.isRecent) {
        let url = this.res.target + "/new100.html";
        let response = await Vue.http.get(url);
        let $ = cheerio.load(response.data);
        let hrefs = $(
          "body > div.warp > div.top_warp > div.top-min.top-min-long.new100 > ul > li > h5 > a"
        );
        for (let i = 0; i < hrefs.length; i++) {
          let href = hrefs[i];
          let movieUrl = targetHost + $(href).attr("href");
          try {
            let movieResponse = await Vue.http.get(movieUrl);
            console.log(movieUrl);
            let movie$ = cheerio.load(movieResponse.data);
            let time = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(12) > label"
            )
              .text()
              .replace("时间：", "");
            let name = movie$("h1").text();
            let movie = {
              name: name,
              status: "收集信息",
            };
            this.movies.splice(0, 0, movie);
            movie.time = time;
            let formData = new URLSearchParams();
            movie.status = "检查重复";
            let repeatName = new URLSearchParams();
            repeatName.append("keyword", name);
            let repeatResponse = await Vue.http.post(
              this.$store.state.account.host +
                "/yuet2/admin_video.php?v_recycled=&v_isunion=&v_ismoney=&v_ispsd=&jqtype=",
              repeatName
            );
            let act = "add";
            let uploadUrl = "";
            if (repeatResponse.data.includes("没有记录")) {
              movie.status = "开始新增";
              let totalMatch = movie$(
                "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(1) > font:nth-child(2)"
              )
                .text()
                .match(/\d+/gi);
              let total = totalMatch ? totalMatch[0] : "";
              formData.append("v_total", total);
            } else {
              act = "edit";
              let id = cheerio
                .load(repeatResponse.data)(
                  "body > div.r_main > div > div > table > tbody > tr:nth-child(6) > td:nth-child(1)"
                )
                .text()
                .trim();
              formData.append("v_id", id);
              let editResponse = await Vue.http.get(
                this.$store.state.account.host +
                  "/yuet2/admin_video.php?action=edit&id=" +
                  id
              );
              let edit$ = cheerio.load(editResponse.data);
              uploadUrl = edit$("#v_pic").val();
              movie.status = "开始覆盖";
              formData.append("v_ver", edit$("input[name='v_ver']").val());
              formData.append("v_tags", edit$("input[name='v_tags']").val());
              formData.append(
                "v_douban",
                edit$("input[name='v_douban']").val()
              );
              let playerArea = edit$("#v_playarea");
              let playSelect = playerArea.find("select");
              let playTextareas = playerArea.find("textarea");
              _.each(playSelect, (player) => {
                formData.append(
                  edit$(player).attr("name"),
                  edit$(player).val()
                );
              });
              _.each(playTextareas, (playTextarea) => {
                formData.append(
                  edit$(playTextarea).attr("name"),
                  edit$(playTextarea)
                    .val()
                    .replace(/\n/gi, "\r\n")
                );
              });
              let total = edit$("input[name='v_total']").val();
              formData.append("v_total", total);
            }
            formData.append("v_name", name);
            let infoTitle = movie$(".info-title").text();
            let year = infoTitle.includes("2")
              ? infoTitle.match(/\d{4}/gi)[0]
              : "";
            formData.append("v_publishyear", year);
            let nickname = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(2)"
            )
              .text()
              .replace("原名：", "");
            let alias = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(3)"
            )
              .text()
              .replace("别名：", "")
              .replace(/\//, ",");
            movie.nickname = nickname + "," + alias;
            formData.append("v_nickname", movie.nickname);
            console.log("原名搞定");
            let company = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(4) > span:nth-child(2)"
            ).text();
            formData.append("v_company", company);
            movie.company = company;
            let director = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(5) > span:nth-child(2)"
            ).text();
            formData.append("v_director", director);
            let actor = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(6) > span"
            ).text();
            formData.append("v_actor", actor);
            let subCategoryNodes = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(9) > label a"
            );
            let subCategories = subCategoryNodes
              .toArray()
              .map((x) => movie$(x).text())
              .join(",");
            formData.append("v_jqtype_extra[]", subCategories);
            let publishArea = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(10) > label"
            )
              .text()
              .replace("地区：", "");
            formData.append("v_publisharea", publishArea);
            let tv = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(11) > label"
            )
              .text()
              .replace("电视台：", "");
            formData.append("v_tvs", tv);
            movie.tv = tv;
            let len = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(11) > span"
            )
              .text()
              .replace("单集片长：", "")
              .replace("分", "")
              .replace("钟", "");
            formData.append("v_len", len);
            let note = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(1) > font:nth-child(1)"
            ).text();
            formData.append("v_note", note);
            var desc = movie$("body > div.warp > div.o_cn2 > div.des_box > div")
              .text()
              .replace("剧情介绍：", "");
            formData.append("v_content", desc);
            let v_longtxt = movie$("span.fybj").text();
            formData.append("v_longtxt", v_longtxt);
            if (!uploadUrl) {
              let imgUrl = movie$(
                "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_list > div > img"
              ).attr("src");
              let retryCount = 5;
              let imgResponse;
              function sleep(ms) {
                return new Promise((resolve) => setTimeout(resolve, ms));
              }
              while (retryCount-- >= 0) {
                try {
                  imgResponse = await Vue.http.get(imgUrl, {
                    responseType: "arraybuffer",
                  });
                  break;
                } catch (e) {
                  await sleep(1000);
                }
              }
              if (!imgResponse) {
                movie.status = "图片下载失败(" + movieUrl + ")";
                continue;
              }
              let imgUri = new URL(imgUrl);
              let imgType = imgUri.pathname.split(".");
              imgType = imgType[imgType.length - 1];
              let imgForm = new FormData();
              let imgBlob = new Blob([imgResponse.data], {
                type: "img/" + imgType,
              });
              imgForm.append("file1", imgBlob, "test." + imgType);
              let imgUploadResponse = await Vue.http.post(
                this.$store.state.account.host + "/yuet2/upload.php",
                imgForm,
                {
                  headers: {
                    "Content-Type": "multipart/form-data;charset=UTF-8",
                  },
                }
              );
              uploadUrl = imgUploadResponse.data
                .match(/value='.*?uploads.*?'/gi)[0]
                .split("=")[1]
                .replace(/'/gi, "");
            }
            formData.append("v_pic", uploadUrl);
            let fromTabs = [];
            let tabIndex = 0;
            let tabContent = movie$(".down_list ul");
            let downFroms = {};
            let downUrls = {};
            _.each(movie$(".from-tabs label"), (tab) => {
              let targetSource = movie$(tab)
                .text()
                .replace(/\[.*?]/gi, "");
              let downloadSourceLabel = downloadMap[targetSource];
              let currentTabContent = tabContent[tabIndex];
              let hrefs = movie$(currentTabContent).find("li a");
              downFroms["m_downfrom[" + (tabIndex + 1) + "]"] = targetSource;
              let urls = [];
              _.each(hrefs, (href) => {
                urls.push(
                  movie$(href).text() +
                    "$" +
                    movie$(href).attr("href") +
                    "$" +
                    downloadSourceLabel
                );
              });
              downUrls["m_downurl[" + (tabIndex + 1) + "]"] = urls.join("\r\n");
              tabIndex++;
            });
            console.dir(downFroms);
            for (var key in downFroms) {
              formData.append(key, downFroms[key]);
            }
            console.dir(downUrls);
            for (var key in downUrls) {
              formData.append(key, downUrls[key]);
            }
            let type = movie$(
              "body > div.warp > div.position.w960.fn-clear > div > a:nth-child(2)"
            ).text();
            movie.category = type;
            type = this.existsTypes.filter((x) => x.name == type)[0].id;
            formData.append("v_type", type);
            let addResponse = await Vue.http.post(
              this.$store.state.account.host +
                "/yuet2/admin_video.php?action=save&acttype=" +
                act,
              formData
            );
            movie.status = "√";
          } catch (e) {
            console.error(e);
            console.log("电影失败：" + movieUrl);
          }
        }
        return;
      }
      this.page = 1;
      this.pageCount = 10000000;
      let begin = 0;
      let end = 0;
      let go = null;
      let reach = null;
      if (onlyToday) {
        begin = this.page;
        reach = () => begin <= end;
        go = () => {
          begin++;
          this.page++;
        };
        end = this.pageCount;
      } else {
        begin = this.pageCount;
        end = 1;
        go = () => {
          begin--;
          this.page--;
        };
        reach = () => begin >= end;
        this.page = begin;
      }
      for (; reach(); go()) {
        let response = await Vue.http.get(
          this.res.target + "/" + this.page + "_______.html"
        );
        let $ = cheerio.load(response.data);
        let movieNodes = $(".list_20 a").toArray();
        let pagers = $(
          "body > div.warp > div.list3_cn_box > div:nth-child(3) > a"
        );
        if (onlyToday) {
          this.end = this.pageCount;
        } else if (this.pageCount == 10000000) {
          this.begin = this.page = this.pageCount = pagers.length
            ? $(pagers[pagers.length - 1])
                .attr("href")
                .match(/\/\d+\_/gi)[0]
                .match(/\d+/gi)[0]
            : 1;
        }
        for (var node in movieNodes) {
          node = movieNodes[node];
          let movieUrl = targetHost + $(node).attr("href");
          try {
            let movieResponse = await Vue.http.get(movieUrl);
            console.log(movieUrl);
            let movie$ = cheerio.load(movieResponse.data);
            let time = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(12) > label"
            )
              .text()
              .replace("时间：", "");
            let name = movie$("h1").text();
            let movie = {
              name: name,
              status: "收集信息",
            };
            this.movies.splice(0, 0, movie);
            movie.time = time;
            if (
              onlyToday &&
              new Date(Date.parse(time)).getDate() !=
                new Date(Date.now()).getDate()
            ) {
              movie.status = "不是今日，采集完成";
              return;
            }
            let formData = new URLSearchParams();
            movie.status = "检查重复";
            let repeatName = new URLSearchParams();
            repeatName.append("keyword", name);
            let repeatResponse = await Vue.http.post(
              this.$store.state.account.host +
                "/yuet2/admin_video.php?v_recycled=&v_isunion=&v_ismoney=&v_ispsd=&jqtype=",
              repeatName
            );
            let act = "add";
            let uploadUrl = "";
            if (repeatResponse.data.includes("没有记录")) {
              movie.status = "开始新增";
              let totalMatch = movie$(
                "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(1) > font:nth-child(2)"
              )
                .text()
                .match(/\d+/gi);
              let total = totalMatch ? totalMatch[0] : "";
              formData.append("v_total", total);
            } else {
              act = "edit";
              let id = cheerio
                .load(repeatResponse.data)(
                  "body > div.r_main > div > div > table > tbody > tr:nth-child(6) > td:nth-child(1)"
                )
                .text()
                .trim();
              console.log(id);
              formData.append("v_id", id);
              let editResponse = await Vue.http.get(
                this.$store.state.account.host +
                  "/yuet2/admin_video.php?action=edit&id=" +
                  id
              );
              let edit$ = cheerio.load(editResponse.data);
              uploadUrl = edit$("#v_pic").val();
              movie.status = "开始覆盖";

              formData.append("v_ver", edit$("input[name='v_ver']").val());
              formData.append("v_tags", edit$("input[name='v_tags']").val());
              formData.append(
                "v_douban",
                edit$("input[name='v_douban']").val()
              );
              let playerArea = edit$("#v_playarea");
              let playSelect = playerArea.find("select");
              let playTextareas = playerArea.find("textarea");
              _.each(playSelect, (player) => {
                formData.append(
                  edit$(player).attr("name"),
                  edit$(player)
                    .val()
                    .replace(/\n/gi, "\r\n")
                );
              });
              _.each(playTextareas, (playTextarea) => {
                formData.append(
                  edit$(playTextarea).attr("name"),
                  edit$(playTextarea).val()
                );
              });
              let total = edit$("input[name='v_total']").val();
              formData.append("v_total", total);
            }
            formData.append("v_name", name);
            let infoTitle = movie$(".info-title").text();
            let year = infoTitle.includes("2")
              ? infoTitle.match(/\d{4}/gi)[0]
              : "";
            formData.append("v_publishyear", year);
            let nickname = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(2)"
            )
              .text()
              .replace("原名：", "");
            let alias = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(3)"
            )
              .text()
              .replace("别名：", "")
              .replace(/\//, ",");
            movie.nickname = nickname + "," + alias;
            formData.append("v_nickname", movie.nickname);
            console.log("原名搞定");
            let company = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(4) > span:nth-child(2)"
            ).text();
            formData.append("v_company", company);
            movie.company = company;
            let director = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(5) > span:nth-child(2)"
            ).text();
            formData.append("v_director", director);
            let actor = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(6) > span"
            ).text();
            formData.append("v_actor", actor);
            let subCategoryNodes = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(9) > label a"
            );
            let subCategories = subCategoryNodes
              .toArray()
              .map((x) => movie$(x).text())
              .join(",");
            formData.append("v_jqtype_extra[]", subCategories);
            let publishArea = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(10) > label"
            )
              .text()
              .replace("地区：", "");
            formData.append("v_publisharea", publishArea);
            let tv = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(11) > label"
            )
              .text()
              .replace("电视台：", "");
            formData.append("v_tvs", tv);
            movie.tv = tv;
            let len = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(11) > span"
            )
              .text()
              .replace("单集片长：", "")
              .replace("分", "")
              .replace("钟", "");
            formData.append("v_len", len);
            let note = movie$(
              "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_r_contact_all > div.o_r_contact > ul > li:nth-child(1) > font:nth-child(1)"
            ).text();
            formData.append("v_note", note);
            var desc = movie$("body > div.warp > div.o_cn2 > div.des_box > div")
              .text()
              .replace("剧情介绍：", "");
            formData.append("v_content", desc);
            let v_longtxt = movie$("span.fybj").text();
            formData.append("v_longtxt", v_longtxt);
            if (!uploadUrl) {
              let imgUrl = movie$(
                "body > div.warp > div.o_r_t_wap.pr > div.info-box > div.o_list > div > img"
              ).attr("src");
              let retryCount = 5;
              let imgResponse;
              function sleep(ms) {
                return new Promise((resolve) => setTimeout(resolve, ms));
              }
              while (retryCount-- >= 0) {
                try {
                  imgResponse = await Vue.http.get(imgUrl, {
                    responseType: "arraybuffer",
                  });
                  break;
                } catch (e) {
                  await sleep(1000);
                }
              }
              if (!imgResponse) {
                movie.status = "图片下载失败(" + movieUrl + ")";
                continue;
              }
              let imgUri = new URL(imgUrl);
              let imgType = imgUri.pathname.split(".");
              imgType = imgType[imgType.length - 1];
              let imgForm = new FormData();
              let imgBlob = new Blob([imgResponse.data], {
                type: "img/" + imgType,
              });
              imgForm.append("file1", imgBlob, "test." + imgType);
              let imgUploadResponse = await Vue.http.post(
                this.$store.state.account.host + "/yuet2/upload.php",
                imgForm,
                {
                  headers: {
                    "Content-Type": "multipart/form-data;charset=UTF-8",
                  },
                }
              );
              uploadUrl = imgUploadResponse.data
                .match(/value='.*?uploads.*?'/gi)[0]
                .split("=")[1]
                .replace(/'/gi, "");
            }
            formData.append("v_pic", uploadUrl);
            let fromTabs = [];
            let tabIndex = 0;
            let tabContent = movie$(".down_list ul");
            let downFroms = {};
            let downUrls = {};
            _.each(movie$(".from-tabs label"), (tab) => {
              let targetSource = movie$(tab)
                .text()
                .replace(/\[.*?]/gi, "");
              let downloadSourceLabel = downloadMap[targetSource];
              let currentTabContent = tabContent[tabIndex];
              let hrefs = movie$(currentTabContent).find("li a");
              downFroms["m_downfrom[" + (tabIndex + 1) + "]"] = targetSource;
              let urls = [];
              _.each(hrefs, (href) => {
                urls.push(
                  movie$(href).text() +
                    "$" +
                    movie$(href).attr("href") +
                    "$" +
                    downloadSourceLabel
                );
              });
              downUrls["m_downurl[" + (tabIndex + 1) + "]"] = urls.join("\r\n");
              tabIndex++;
            });
            console.dir(downFroms);
            for (var key in downFroms) {
              formData.append(key, downFroms[key]);
            }
            console.dir(downUrls);
            for (var key in downUrls) {
              formData.append(key, downUrls[key]);
            }
            let type = movie$(
              "body > div.warp > div.position.w960.fn-clear > div > a:nth-child(2)"
            ).text();
            movie.category = type;
            type = this.existsTypes.filter((x) => x.name == type)[0].id;
            formData.append("v_type", type);
            let addResponse = await Vue.http.post(
              this.$store.state.account.host +
                "/yuet2/admin_video.php?action=save&acttype=" +
                act,
              formData
            );
            movie.status = "√";
          } catch (e) {
            console.error(e);
            console.log("电影失败：" + movieUrl);
          }
        }
      }
    },
    async createBind(category, targetCategory) {
      let apiUrl =
        this.$store.state.account.host +
        "/yuet2/admin_reslib.php?ac=bindsubmit&curid=" +
        category.loadId +
        "&tid=" +
        targetCategory +
        "&v_oldtype=1&timestamp=1598760978919";
      let response = await Vue.http.get(apiUrl);
      if (response.data == "nobind") {
        category.status = "未绑定";
      } else {
        category.status = "已绑定";
      }
    },
    async selectCategory(category) {
      this.page = 1;
      this.listUrl =
        this.$store.state.account.host +
        "/yuet2/admin_reslib.php" +
        category.url;
      let response = await Vue.http.get(this.listUrl);
      const cheerio = require("cheerio");
      const $ = cheerio.load(response.data);
      let movieRes = [];
      let movieList = $("#cpcontainer > table > tbody:nth-child(15) > tr");
      _.each(movieList, (movie) => {
        let tds = $(movie).find("td");
        movieRes.push({
          name: $(tds[0]).text(),
          category: $(tds[1]).text(),
          source: $(tds[2]).text(),
          time: $(tds[3]).text(),
        });
      });
      console.dir(movieRes);
      this.movies = movieRes.slice(0, movieRes.length - 1);
    },

    async select(res) {
      this.res = res;
      this.resTitle = "资源库(" + res.label + ")";
      this.page = 1;
      if (res.label.includes("扩展")) {
        return;
      }
      this.listUrl = this.$store.state.account.host + "/yuet2/" + res.url;
      let response = await Vue.http.get(this.listUrl);
      const cheerio = require("cheerio");
      let $ = cheerio.load(response.data);
      let categoryList = $(
        "#cpcontainer > table > thead > tr:nth-child(2) > th > ul > li"
      );
      let categoryRes = [];
      _.each(categoryList, (category) => {
        categoryRes.push({
          name: $(category)
            .find("a")
            .first()
            .text(),
          status: $(category)
            .find("label b a")
            .text(),
          onclick: $(category)
            .find("label b a")
            .attr("onclick"),
          url: $(category)
            .find("a")
            .first()
            .attr("href"),
          value: "",
        });
      });
      this.categories = categoryRes;

      let movieRes = [];
      let movieList = $("#cpcontainer > table > tbody:nth-child(15) > tr");
      _.each(movieList, (movie) => {
        let tds = $(movie).find("td");
        movieRes.push({
          name: $(tds[0]).text(),
          category: $(tds[1]).text(),
          source: $(tds[2]).text(),
          time: $(tds[3]).text(),
        });
      });
      this.movies = movieRes.slice(0, movieRes.length - 1);
      let pageDoms = $(
        "#cpcontainer > table > thead > tr:nth-child(3) > th > div > div > a"
      );
      _.each(this.categories, (category) => {
        if (!category.onclick) {
          return;
        }
        category.loadId = this.categories
          .filter((x) => x.onclick)[0]
          .onclick.match(/\d+\_\d+/gi)[0];
      });
      let categoryLoadId = this.categories.filter((x) => x.loadId)[0].loadId;
      let apiUrl =
        this.$store.state.account.host +
        "/yuet2/admin_reslib.php?curid=" +
        categoryLoadId +
        "&ac=bind&classid=0&timestamp=1598758433029";
      let response1 = await Vue.http.get(apiUrl);
      $ = cheerio.load(response1.data);
      let opts = [];
      _.each($("option"), (option) => {
        opts.push({
          label: this.htmlDecode($(option).html()),
          value: $(option).val(),
        });
      });
      this.options = opts;
      console.dir(this.options);
    },
    htmlDecode(html) {
      let div = document.createElement("div");
      div.innerHTML = html;
      return div.innerText || div.textContent;
    },
    onSubmit() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let url = new URL(this.form.url);
          this.form.host = url.protocol + "//" + url.hostname;
          this.$store.state.account = this.form;
          if (await Login(this.form)) {
            this.hasAccount = true;
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
html {
  height: 100%;
  width: 100%;
  display: flex;
}
body {
  flex: 1;
  display: flex;
}
#app {
  flex: 1;
}
.login {
  align-self: center;
  margin: 0 auto;
}
</style>
